const fs = require("fs");
const fsExtra = require("fs-extra");
const path = require("path");
const axios = require("axios");
const { inspect } = require("util");
const c = require("ansi-colors");


const generateImageUrl = (emojiType, emojiOriginClassName) => {
  let handledEmojiClassName = emojiOriginClassName
    .replace(/emoji/g, "emoji_u")
    .replace(/-/g, "_")
    .replace(/_fe0f/g, "");
  let emojiRemoteUrl = `https://pic.sopili.net/pub/emoji/noto-emoji/png/128/${handledEmojiClassName}.png`;
  if (emojiType === "flags") {
    handledEmojiClassName = emojiOriginClassName.replace("emoji", "");
    emojiRemoteUrl = `https://pic.sopili.net/pub/emoji/twitter/2/72x72/${handledEmojiClassName}.png`;
  }
  return emojiRemoteUrl;
};

const downloadAjax = async (url, filePath) => {
  // 获取文件名
  const parsedUrl = new URL(url);
  const filename = path.basename(parsedUrl.pathname) || `file_${Date.now()}`;
  try {
    // 开始下载
    console.log(c.blue.bold(`\n开始下载： ${c.green.bold.underline(`${url}`)}`));
    // const response = await axios({
    //   url,
    //   method: "GET",
    //   responseType: "stream",
    // });

    // const writer = fs.createWriteStream(`${filePath}/${filename}`);
    // response.data.pipe(writer);

    // await new Promise((resolve, reject) => {
    //   writer.on("finish", resolve);
    //   writer.on("error", reject);
    // });

    const response = await axios.get(url, { responseType: "arraybuffer" });
    fs.writeFileSync(`${filePath}/${filename}`, response.data);
    // console.log(`\n文件已保存至：${filePath}/${filename}}`);
    // console.log(c.blue.bold(`\n文件已保存至： ${c.green.bold.underline(`${filePath}/${filename}`)}`));
  } catch (error) {
    // console.error(`${c.red(`下载失败：${error.message}`)}`);
    console.log(c.red.bold(`\n下载失败： ${c.red(`${error.message}`)}`));
  }
};

const readAllFiles = async (dirPath, origin) => {
  try {
    let pathArray = [];
    // 读取指定目录下的所有内容
    const files = await fsExtra.readdir(dirPath);
    for (const fileName of files) {
      let filePath = "";
      if (origin) {
        const relativePath = path.relative(process.cwd(), dirPath);
        filePath = `${origin.replace(/\/+$/, "")}/${relativePath.replace(
          /\\/g,
          "/"
        )}/${fileName}`;
      } else {
        filePath = path.join(dirPath, fileName);
      }

      // 获取文件或目录的详细信息
      const stat = await fsExtra.stat(path.join(dirPath, fileName));
      if (stat.isDirectory()) {
        // 如果是目录，则递归调用 readAllFiles 函数
        await readAllFiles(filePath);
      } else {
        pathArray.push({
          fileName,
          filePath,
        });
      }
    }
    return pathArray;
  } catch (err) {
    console.error("发生错误:", err);
  }
};

// 根据参数获取下载路径
const generateDownloadPathList = (typeList, directory) => {
  let emojiOptions = [];
  for (let emojiType of typeList) {
    emojiOptions.push({
      emojiType,
      filePath: path.join(process.cwd(), `${directory}/${emojiType}`),
    });
  }
  return emojiOptions;
};

/**
 * 将对象写入 JS 文件并导出
 * @param {Object} obj - 要导出的对象
 * @param {string} filePath - 目标 JS 文件路径
 */
const writeObjectToModule = async (obj, filePath) => {
  const objectString = inspect(obj, {
    depth: null, // 无限递归层级
    compact: false, // 不使用紧凑格式
    sorted: false, // 对象键名排序
    maxArrayLength: null, // 不限制数组长度
    maxStringLength: null, // 不截断字符串
  });

  // 构建文件内容
  const content = `const data = ${objectString}; \n\n module.exports = data`;

  // 确保目录存在并写入文件
  await fsExtra.outputFile(path.resolve(filePath), content);
};

module.exports = {
  generateImageUrl,
  downloadAjax,
  readAllFiles,
  generateDownloadPathList,
  writeObjectToModule,
};
